//js基础类扩展极 自定义工具类
/**
 * 扩展基础类
 * 得到字符串的长度，包括中文和英文
 **/
String.prototype.charlen = function() {
	var arr = this.match(/[^\x00-\xff]/ig);
	return this.length + (arr == null ? 0 : arr.length);
}

/**
 * 扩展基础类
 * 格式化字符串${0} -> 参考printf %s
 **/
String.prototype.format = function() {
	var args = arguments;
	return this.replace(/\$\{(\d+)\}/g,              
		function(m, i){
			return args[i];
		});
} 

/**
 * 扩展基础类
 * 字符串首尾去空格
 **/
String.prototype.trim = function() {
	return this.replace(/(^\s*)|(\s*$)/g, "");
}

/**
 * 扩展基础类
 * 字符串包含字符串判断
 **/
String.prototype.contains = function(sub) {
	return this.indexOf(sub) != -1;
}

/**
 * 扩展基础类
 * 字符串比较大小
 **/
String.prototype.compare = function(b) {
	if(!b)
		return -1;

	if(this.length != b.length)
		return this.length - b.length;

	var i = 0;
	for (; i < this.length; i++){
		var val = this.charCodeAt(i) - b.charCodeAt(i);
		if(val != 0)
			return val;
	}

	return 0;
}

/**
 * 扩展基础类
 * 替换字符
 **/
String.prototype.replaceLen = function(start, len, replaced) {
	if(!len)
		return this;

	if(start >= this.length)
		return this;

	var returnSeg = '';
	var returnSeg2 = '';
	var i = 0;
	for (; i < this.length; i++){
		var c = this.charAt(i);
		if(i < start)
			returnSeg += c;

		if(i >= start + len)
			returnSeg2 += c;
	}

	return returnSeg + replaced + returnSeg2;
}

/**
 * 扩展基础类
 * 替换字符，这个在替换填入比较有用，比如***天***小时 替换为 <input />天<input />小时
 **/
String.prototype.replaceChar = function(target, replaced, start) {
	if(!target)
		return this;

	if(!start)
		start = 0;

	var returnVal = this.substring(0, start);
	var index = 0;
	for (var i = start; i < this.length; i++) {
		var c = this.charAt(i);
		target = typeof target == 'function' ? target.call(this, index) : target;
		if (c == target) {
			returnVal += typeof replaced == 'function' ? replaced.call(this, index) : replaced;
			while (i < this.length - 1 && this.charAt(i + 1) == c) {
				i++;
			}
			index++;
		}else{
			returnVal += c;
		}
	}

	return returnVal;
}

/**
 * 扩展基础类
 * 克隆复制（简单copy而已）
 **/
Array.prototype.clone = function(){
	var arr = [];
	var i = 0;
	for(; i < this.length; i++){
		switch(typeof this[i]){
			case 'object':
				var obj = {};
				for(key in this[i])
					obj[key] = this[i][key];
				arr.push(obj);
				break;
			default:
				arr.push(this[i]);
				break;
		}
	}
	return arr;
}

/**
 * 扩展基础类
 * 清空
 **/
Array.prototype.clear = function() {
	this.splice(0, this.length);
}

/**
 * 扩展基础类
 * 数组包含元素
 **/
Array.prototype.contains = function(el) {
	var i;
	for(i = 0; i < this.length; i++) {  
		if(this[i] == el)  
			return true;  
	}  
	return false;  
}

/**
 * 扩展基础类
 * 数组添加数组（数组合并）
 **/
Array.prototype.merge = function(arr) {
	if(arr){
		var i;
		for(i = 0; i < arr.length; i++) {  
			this.push(arr[i]);
		}  
	}
}

/**
 * 扩展基础类
 * 根据值和属性获取到数组的对象下标
 **/
Array.prototype.indexOf = function(val, field){
	var i = 0;
	for(; i < this.length; i++){
		if(this[i] && (field ? this[i][field] == val : this[i] == val)){
			return i;
		}
	}
	return -1;
}

/**
 * 扩展基础类
 * 最后一个下标
 **/
Array.prototype.lastIndexOf = function(val, field){
	var i = 0;
	var max = -1;
	for(; i < this.length; i++){
		if(this[i] && (field ? this[i][field] == val : this[i] == val)){
			max = i;
		}
	}
	return max;
}

/**
 * 扩展基础类
 * 数组唯一（去重）
 **/
Array.prototype.unique = function(field){
	var arr = [];

	var i = 0;
	for(; i < this.length; i++){
		var val = field ? this[i][field] : this[i];
		var index = this.lastIndexOf(val, field);
		if(index == i)
			arr.push(this[i]);
	}

	return arr;
}

/**
 * 扩展基础类
 * 数组最大值
 **/
Array.prototype.max = function(field){
	var result = this[0];

	var i = 0;
	for(; i < this.length; i++){
		var val = field ? this[i][field] : this[i];
		if(val > result)
			result = val;
	}

	return result;
}

/**
 * 扩展基础类
 * 数组最小值
 **/
Array.prototype.min = function(field){
	var result = {"value":this[0],"index":0};

	var i = 0;
	for(; i < this.length; i++){
		var val = field ? this[i][field] : this[i];
		if(val < result.value){
			result.value = val;
			result.index = i;
		}	
	}

	return result;
}

/**
 * 扩展基础类
 * 日期格式化
 **/
Date.prototype.format = function(pat){
	var year = this.getFullYear();
	var month = this.getMonth() + 1;
	var day = this.getDate();
	var hour = this.getHours();
	var minute = this.getMinutes();
	var second = this.getSeconds();
	// 两位补齐
	month = month > 9 ? month : "0" + month;
	day = day > 9 ? day : "0" + day;
	hour = hour > 9 ? hour : "0" + hour;
	minute = minute > 9 ? minute : "0" + minute;
	second = second > 9 ? second : "0" + second;
	if(!pat){
		pat = "yyyy-MM-dd";
	}
	pat = pat.replace(/yyyy/g, year);
	pat = pat.replace(/MM/g, month);
	pat = pat.replace(/dd/g, day);
	pat = pat.replace(/HH/gi, hour);
	pat = pat.replace(/mm/g, minute);
	pat = pat.replace(/ss/g, second);
	return pat;
}

// 减去时差的毫秒数（取决于使用的浏览器的locale设置）
Date.prototype.getTime2 = function(){
//			return this.getTime();
	return this.getTime() - this.getTimezoneOffset() / 60 * 3600 * 1000;
}

// 日期相差秒数
Date.prototype.diff = function(date){
	return Math.ceil((this - date) / (1000));
}

// 日期相差天数
Date.prototype.diffdays = function(date){
	return Math.ceil((this - date) / (1000 * 60 * 60 * 24));
}
// 日期加减计算
Date.prototype.add = function(days){
	return new Date(this.getTime() + days * (1000 * 60 * 60 * 24));
}

// 日期加减计算
Date.prototype.addMonth = function(months){
	var day = this.getDate();
	var month = this.getMonth() + 1;
	var year = this.getFullYear();
	month += months;  
	if(month > 12){
		year += Math.floor(month / 12);
		month = month % 12;
	}
	return Date.parse(month + '/' + day + '/' + year);
}

// 解析字符串，以默认 pat = "yyyy-MM-dd"的格式，而不是MM/dd/yyyy
Date.parse2 = function(str, pat){
	if(str == null || str == '')
		return new Date();
	var rstr = str.replace(/(\d{4})([-\./])(\d{1,2})\2(\d{1,2})/, "$3/$4/$1");
	return new Date(Date.parse(rstr));
}

// 解析字符串，json date obj
// 减去时差的毫秒数（取决于使用的浏览器的locale设置）
Date.parse3 = function(obj){
//			return new Date(obj.time);
	return new Date(obj.time - new Date().getTimezoneOffset() / 60 * 3600 * 1000);
//			var str = obj.year + '-' + (obj.month + 1) + '-' + obj.date + ' ' + 
//				obj.hours + ':' + obj.minutes + ':' + obj.seconds;
//			return Date.parse2(str);
}
/* Tool Start */
//函数功能工具类
window.Tool = {
    //获取长度，数字字母一般字符算1个，全角字符中文算2
    len: function(str) {
        if (str == null) {
            return 0;
        }
        return str.replace(/[^\x00-\xff]/g, "**").length;
    },
    getHost: function(url) {
        var host = "";
        if(!url){
            url = window.location.href;
        }
        if (url) {
            var match = url.match(/http:\/\/[^\/]+(?=\/)/g);
            if (match != null && match.length > 0) {
                host = match[0];
            }
        }
        return host;
    }, 
    //替换字符串
    replace: function(str, oldStr, newStr) {
        return str.replace(new RegExp(oldStr, 'g'), newStr);
    },
	//再url后追加参数
    appendParaToUrl: function(url, params) {
        var strPara = $.param(params);
        if (strPara != "") {
            url += (url.indexOf("?") >= 0 ? "&" : "?") + strPara;
        }
        return url;
    },
	//获取文件的扩展名
    getFileExtName: function(fileName) {
        var reg = /\.([^.]+)$/;
        var m = fileName.match(reg);
        return m ? m[1] : "";
    },
    getArrayAverage: function(arr) {
        var result = 0;
        for (var i = 0, len = arr.length; i < len; i++) {
            result += arr[i];
        }
        return parseInt(result / len);
    },
    parseDate: function(dateString) {
        var reg = /^(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)$/;
        var m = dateString.match(reg);
        var date = new Date(m[1], m[2] - 1, m[3], m[4], m[5], m[6]);
        return date;
    },
    getTextTimeSpan: function(seconds) {
        if (seconds <= 0) return "0秒";
        var s = seconds % 60;
        var minutes = parseInt(seconds / 60);
        var m = minutes % 60;
        var hours = parseInt(minutes / 60);
        var text = s + "秒";
        if (m > 0) text = m + "分" + text;
        if (hours > 0) text = hours + "小时" + text;
        return text;
    },
    getSupportUploadType: function() {
        var type = "common";
        if ($.browser.msie) {
            if (isSupportControlUpload_IE()) {
                type = "control";
            } else if (isSupportFlashUpload_IE()) {
                type = "flash";
            }
        } else {
            if (navigator.mimeTypes) {
                var mimetype = navigator.mimeTypes["application/x-richinfo-cxdnd3"];
                var isSafari = navigator.userAgent.indexOf("Safari")>0 && navigator.userAgent.indexOf("Chrome")==-1;
                if (mimetype && mimetype.enabledPlugin && !isSafari) {//苹果浏览器暂时不支持
                    type = "control";
                } else if (isSupportFlashUpload_NotIE()) {
                    type = "flash";
                }
            }
        }
        //必须支持flash上传9.0以上版本
        function isSupportFlashUpload_NotIE() {
            if (navigator.plugins && navigator.plugins.length > 0) {
                var swf = navigator.plugins["Shockwave Flash"];
                if (swf) {
                    var words = swf.description.split(" ");
                    for (var i = 0; i < words.length; ++i) {
                        if (isNaN(parseInt(words[i]))) continue;
                        var flashVersion = parseInt(words[i]);
                        if (flashVersion >= 9) {
                            return true;
                        }
                    }
                }
            } else {
                return false;
            }
        }
        function isSupportFlashUpload_IE() {
            if (window.ActiveXObject) {
                try {
                    var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.10");
                } catch (e) {
                    try {
                        var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.9");
                    } catch (e) { }
                }
                if (flash) return true;
            }
            return false;
        }
        function isSupportControlUpload_IE() {
            return Utils.isUploadControlSetup();
        }
        return type;
    },
    getProgressText: function(number) {
        if (!number) return "0%";
        return parseInt(number * 10000) / 100 + "%";
    },
    getTimeText: function(timespan) {
        if (!timespan || timespan < 0) return "";
        var seconds = parseInt(timespan / 1000);
        if (seconds == 0) return "00:00";
        var s = seconds % 60;
        var minutes = parseInt(seconds / 60);
        var m = minutes % 60;
        var hours = parseInt(minutes / 60);
        var text = (m > 9 ? m : "0" + m) + ":" + (s > 9 ? s : "0" + s);
        if (hours > 0) {
            text = hours + ":" + text;
        }
        return text;
    },     
    getPersentText: function(floatNum) {
        var n = floatNum * 100;
        n = parseInt(n);
        return n + "%";
    }, 
    /*
    mapper              : id与函数名称的映射json
    getFuncFromValue    : 根据json的函数名获取函数
    getAnchorFromKey    : 根据json的id获取jq对象
    */
    registerAnchor: function(mapper, getFuncFromValue, getAnchorFromKey) {
        if (getAnchorFromKey == null) {
            getAnchorFromKey = function(id) {
                return $.getById(id);
            };
        }
        if (getFuncFromValue == null) {
            getFuncFromValue = function(val) {
                return window[val];
            }
        }
        $.each(mapper, function(name, val) {
            var tempEle = getAnchorFromKey(name);
            //alert(tempEle.prev().length);
            //tempEle.add(tempEle.prev()).click(function(e) {
              tempEle.click(function(e) {
                if (tempEle.length > 0 && !tempEle[0].disabled) {
                    var func = getFuncFromValue(val);
                    if (func != null && $.isFunction(func)) {
                        func();
                    }
                }
                e.preventDefault();
            });
        });
    },
    invalidAction: function() {
        top.location = top.ucDomain + "/Error/systemTip4.html";
    },
    scriptImgError: function(picPath) {
        return "if(this.error){this.alt=\"加载有误\";}else{this.error=1;this.src=\"" + picPath + "\";}";
    },
    getWinSize: function(win) {
        var myWidth = 0, myHeight = 0;
        if (!win) {
            win = window;
            //win = Tool.getDiskWindow();
        }
        var document = win.document;
        if (typeof (win.innerWidth) == 'number') {
            //Non-IE
            myWidth = win.innerWidth;
            myHeight = win.innerHeight;
        }
        else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            //IE 6+ in 'standards compliant mode'
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        }
        else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
            //IE 4 compatible
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
        }
        return [myWidth, myHeight];
    },
	getObjTopLeft:function(obj){//浮动对象在窗口居中
		var st=document.documentElement.scrollTop;//滚动条距顶部的距离
		var sl=document.documentElement.scrollLeft;//滚动条距左边的距离
		var ch=document.documentElement.clientHeight;//屏幕的高度
		var cw=document.documentElement.clientWidth;//屏幕的宽度
		var objH=$(obj).height();//浮动对象的高度
		var objW=$(obj).width();//浮动对象的宽度
		var objT=Number(st)+(Number(ch)-Number(objH))/2;
		var objL=Number(sl)+(Number(cw)-Number(objW))/2;
		return {'top':objT,"left":+objL};
	},
	getPageSize:function() {
                var xScroll,
                yScroll;
                if (window.innerHeight && window.scrollMaxY) {
                    xScroll = window.innerWidth + window.scrollMaxX;
                    yScroll = window.innerHeight + window.scrollMaxY + 500
                } else if (document.body.scrollHeight > document.body.offsetHeight) {
                    xScroll = document.body.scrollWidth;
                    yScroll = document.body.scrollHeight + 500
                } else {
                    xScroll = document.body.offsetWidth;
                    yScroll = document.body.offsetHeight + 500
                }
                var windowWidth,
                windowHeight;
                if (self.innerHeight) {
                    if (document.documentElement.clientWidth) {
                        windowWidth = document.documentElement.clientWidth
                    } else {
                        windowWidth = self.innerWidth
                    }
                    windowHeight = self.innerHeight
                } else if (document.documentElement && document.documentElement.clientHeight) {
                    windowWidth = document.documentElement.clientWidth;
                    windowHeight = document.documentElement.clientHeight
                } else if (document.body) {
                    windowWidth = document.body.clientWidth;
                    windowHeight = document.body.clientHeight
                }
                if (yScroll < windowHeight) {
                    pageHeight = windowHeight
                } else {
                    pageHeight = yScroll
                }
                if (xScroll < windowWidth) {
                    pageWidth = xScroll
                } else {
                    pageWidth = windowWidth
                }
                arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
                return arrayPageSize
        }
};

/* Tool End */
/** 开启cookie **/
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 30 * 60 * 60 * 1000))
            } else {
                date = options.expires
            }
            expires = '; expires=' + date.toUTCString()
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure': '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('')
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break
                }
            }
        }
        return cookieValue
    }
};


